<template>
  <div class="add-box">
    <div class="permiss-box">
      <span class="title">角色权限预览</span>
      <el-form
        ref="roleForm"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="rangeName">
          <el-input
            v-model="formData.rangeName"
            :disabled="['detail'].includes(popConfig.popType)"
            clearable
            placeholder="请输入角色名称"
          />
        </el-form-item>
        <el-form-item label="角色编码" prop="rangeCode">
          <el-input
            v-model="formData.rangeCode"
            :disabled="['edit', 'detail'].includes(popConfig.popType)"
            clearable
            placeholder="请输入角色编码"
            maxlength="64"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="formData.remark"
            :disabled="['detail'].includes(popConfig.popType)"
            type="textarea"
            clearable
            placeholder="请输入备注信息"
            maxlength="500"
            resize="none"
          />
        </el-form-item>
      </el-form>
    </div>
    <div class="permiss-box data-limit-box">
      <span class="title">数据权限</span>
      <div class="limit-select">
        <span class="title limit-title">权限范围</span>
        <el-select
          v-model="formData.rangeLevel"
          :disabled="['detail'].includes(popConfig.popType)"
          placeholder="请选择数据权限"
          :style="{ width: '70%' }"
          @change="changeLevel"
        >
          <el-option
            v-for="(item, index) in dictOptions[
              'ecp-admin.dataRange.rangeLevel'
            ]"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div
        v-show="
          formData.rangeLevel !== 'all' &&
            !['detail'].includes(popConfig.popType)
        "
        class="data-info"
      >
        <div class="header-box mb-10">
          <el-checkbox
            v-model="isSelectAll2"
            class="mt-10"
            @change="selectAll2('dataTree', 'sceneIdList')"
          >全选/全不选</el-checkbox>
          <el-checkbox
            v-model="isExpand2"
            @change="expandAll2('dataTree')"
          >展开/折叠</el-checkbox>
          <el-checkbox v-model="isLink">父子联动</el-checkbox>
        </div>
        <el-tree
          ref="dataTree"
          v-loading="loading"
          show-checkbox
          default-expand-all
          :check-strictly="!isLink"
          node-key="value"
          :data="sceneIdList"
          :props="deptDefaultProps"
        />
      </div>
      <div
        v-if="['detail'].includes(popConfig.popType)"
        v-loading="permissLoading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(255, 255, 255, 1)"
        class="content"
        style="overflow: auto;"
      >
        <el-tree
          ref="permissTreeRef"
          :data="sceneIdList"
          node-key="value"
          :default-expand-all="true"
          :props="{ children: 'children', label: 'label' }"
          highlight-current
        />
      </div>
    </div>
  </div>
</template>

<script>
import { dictMixin } from '@/mixin/dict'
import { parseSceneDataProject, convertToTree } from '@/utils/scene-data'
import { elementMixin } from '@/mixin/element'

export default {
  name: 'AddRole',
  mixins: [dictMixin, elementMixin],
  props: {
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗配置
    popConfig: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        rangeName: '',
        rangeCode: '',
        remark: '',
        rangeLevel: 'all'
      },
      // 菜单权限参数
      loading: false,
      permissLoading: false,
      // 数据权限参数
      deptLoading: false,
      isLink: true,
      deptDefaultProps: {
        children: 'children',
        label: 'label',
        value: 'value'
      },
      deptDefaultChecked: [],
      sceneIdList: [],
      rules: {
        rangeName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            required: true,
            message: '角色名称长度过长',
            max: 24,
            trigger: 'blur'
          }
        ],
        rangeCode: [
          { required: true, message: '请输入角色编码', trigger: 'blur' }
        ]
      },
      dictCode: ['ecp-admin.dataRange.rangeLevel']
    }
  },
  watch: {
    popData: {
      handler(data) {
        if (data) {
          let formFields = []
          if (this.popConfig.popType === 'edit') {
            formFields = ['rangeName', 'rangeCode', 'remark', 'status']
          } else {
            formFields = []
          }
          for (const key in this.popData) {
            if (
              Object.hasOwnProperty.call(this.popData, key) &&
              formFields.includes(key)
            ) {
              this.$set(this.formData, key, this.popData[key])
            }
          }
        }
        if (['edit', 'detail'].includes(this.popConfig.popType)) {
          this.getAuthData({
            id: this.popData.id
          })
        }
      },
      deep: true,
      immediate: true
    },
    confirm: {
      handler(confirm) {
        this.submit()
      }
    },
    sceneIdList: {
      handler(val) {
        if (val && val.length && this.deptDefaultChecked.length) {
          this.handlerShowRange()
        }
      },
      deep: true
    },
    deptDefaultChecked: {
      handler(val) {
        if (val && val.length && this.sceneIdList.length) {
          this.handlerShowRange()
        }
      },
      deep: true
    }
  },
  created() {},
  methods: {
    handlerShowRange() {
      this.$refs.dataTree.setCheckedKeys([]) // 先清空选中
      this.$nextTick(() => {
        const that = this
        that.deptDefaultChecked.forEach((i, n) => {
          that.$refs.dataTree.setChecked(that.deptDefaultChecked[n], true)
        })
      })
    },
    async addRole(params) {
      const res = await this.$api.dataRange.add(params)
      if (res.code === '1000') {
        this.$message.success('添加成功！')
        this.$emit('onFinish', 'add-role')
      } else {
        console.log('添加异常')
      }
    },
    async editRole(params) {
      params.id = this.popData.id
      const res = await this.$api.dataRange.update(params)
      if (res.code === '1000') {
        this.$message.success('修改成功！')
        this.$emit('onFinish', 'add-role')
      } else {
        console.log('修改异常')
      }
    },
    /**
     * 提交
     */
    submit() {
      if (this.popConfig.popType === 'detail') {
        this.$emit('onClose', 'detail-role')
        return
      }
      this.$refs.roleForm.validate((valid) => {
        if (valid) {
          if (!this.formData.rangeLevel) {
            this.$message.error('权限范围不能为空')
            return
          }

          // 获取选中的机构权限列表
          let sceneIdList = []
          if (this.formData.rangeLevel !== 'all') {
            const deptCheckedKeys = this.$refs.dataTree.getCheckedNodes() || [] // 全选
            sceneIdList = [...deptCheckedKeys]
              .filter((e) => {
                return e.type === this.formData.rangeLevel
              })
              .map((e) => e.value)
            if (!sceneIdList.length) {
              this.$message.error('数据权限不能为空')
              return
            }
          }
          const { rangeName, rangeCode, rangeLevel, remark } = this.formData
          const params = {
            rangeName,
            rangeCode,
            rangeLevel,
            remark,
            sceneIdList
          }
          if (this.popConfig.popType === 'edit') {
            this.editRole(params)
          } else {
            this.addRole(params)
          }
        } else {
          return false
        }
      })
    },
    // 获取用户权限信息
    async getAuthData(params) {
      this.loading = true
      try {
        const res = await this.$api.dataRange.detail(params)
        if (res.code === '1000') {
          const { sceneIdList = [], rangeLevel } = res.data || {}
          const formFields = [
            'rangeName',
            'rangeCode',
            'remark',
            'status',
            'rangeLevel'
          ]
          for (const key in res.data) {
            if (
              Object.hasOwnProperty.call(res.data, key) &&
              formFields.includes(key)
            ) {
              this.$set(this.formData, key, res.data[key])
            }
          }

          this.$set(this, 'deptDefaultChecked', sceneIdList || [])
          this.changeLevel(rangeLevel, sceneIdList)
        }
        this.loading = false
      } catch (error) {
        console.log(error)
        this.loading = false
      }
    },
    // 数据权限范围
    async changeLevel(e, sceneIdList) {
      if (!e) return
      try {
        if (e === 'all') return
        this.loading = true
        this.$refs.dataTree.setCheckedKeys([]) // 先清空选中
        const res = await this.$api.dataRange.querySceneList({
          id: e
        })
        if (res.code === '1000') {
          let arrTree = []
          let newData = []
          if (this.popConfig.popType === 'detail') {
            arrTree = this.handlerShowData(res.data, sceneIdList) || []
          }

          newData = this.popConfig.popType === 'detail' ? arrTree : (res.data || [])
          switch (e) {
            case 'project':
              arrTree = newData.map((e) => {
                return {
                  ...e,
                  label: e.projectName,
                  value: e.sceneProjectId,
                  type: 'project'
                }
              })
              break
            case 'company':
              arrTree = convertToTree(newData)
              break

            default:
              arrTree = parseSceneDataProject(newData)
              break
          }
          console.log('00-0-0-arrTree', arrTree, e)
          this.sceneIdList = arrTree || []
        }
        this.loading = false
      } catch (error) {
        this.loading = false
        console.log(error)
      }
    },
    // 处理数据
    handlerShowData(dataList, sceneIdList) {
      if (!dataList || !dataList.length) return
      const newData = dataList.filter((e) => {
        return (
          sceneIdList.includes(e.sceneProjectId) ||
          sceneIdList.includes(e.sceneEdificeId) ||
          sceneIdList.includes(e.sceneFloorId) ||
          sceneIdList.includes(e.id) ||
          sceneIdList.includes(e.companyId)
        )
      })
      return newData || []
    }
  }
}
</script>

<style lang="scss" scoped>
.add-box {
  color: #333;
  display: flex;
  max-height: 50vh;
  border: 1px solid #e7e7e7;

  .permiss-box {
    display: flex;
    flex-direction: column;
    padding: 14px;
    width: 50%;
    &.data-limit-box {
      border-left: 1px solid #e7e7e7;
    }
    .title {
      font-size: 14px;
      font-weight: 500;
      color: #303133;
    }
    .el-form {
      margin-top: 16px;
    }
  }
  .menu-info {
    margin-top: 14px;
    flex: 1;
    overflow-y: auto;
  }

  .data-info {
    margin-top: 14px;
    flex: 1;
    overflow-y: auto;
  }

  .limit-select {
    margin-top: 14px;
  }

  .limit-title {
    margin-right: 14px;
  }
}
</style>
